package com.kitty.game.admin.service;

import com.kitty.common.db.Db4CommonService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.admin.message.ReqAdminMakeEquip;
import com.kitty.game.admin.message.RespAdminQueryPlayer;
import com.kitty.game.admin.message.vo.QueryPlayer;
import com.kitty.game.attribute.AttrService;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.base.service.BagService;
import com.kitty.game.config.Equip;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.equip.EquipDataPool;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.model.RoleEquipField;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.market.MarketDataPool;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.role.model.Account;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.AccountService;
import com.kitty.game.server.message.RespOtherLogin;
import com.kitty.game.utils.StringUtil;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.event.EquipUpgradeLevelChangeEvent;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import org.apache.mina.core.session.IoSession;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
//后加
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
//import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;


@Service
public class AdminService {
   // Logger logger = LoggerFunction.GM.getLogger();

    @Autowired
    MallService mallService;
    @Autowired
    EquipService equipService;
    @Autowired
    AttrService attrService;
    @Autowired
    AccountService accountService;
    @Autowired
    ServerService serverService;


    /**
     * 把所有的本地消息都发给在线的GM,避免满地图跑
     */
    public void sendLocalMessage(Message message) {
        DataCache.ONLINE_GMS_ID.stream().map(uid ->
                SpringUtils.getRoleService().getOnlinePlayer(uid)).forEach(role -> MessagePusher.pushMessage(role, message)
        );
    }

    /**
     * GM生成装备
     */
    public void makeEquip(Role role, ReqAdminMakeEquip makeEquip) {
        String equipName = getEquipName(makeEquip.getReq_level(), makeEquip.getEquipType());
        if (StringUtil.isEmpty(equipName)) {
            return;
        }
        List<Integer> polars = Arrays.asList(0, 10, 7, 8, 14, 3);
        int pos = SpringUtils.getBean(BagService.class).getPos(role, false);
        Equip equip = EquipDataPool.getByName(equipName);
        int id = mallService.getRoleEquipId();
        RoleEquip roleEquip = new RoleEquip();
        roleEquip.setId(id);
        roleEquip.setType("装备");
        roleEquip.setName(equipName);
        roleEquip.setRoleId(role.getRoleId());
        roleEquip.setPosition(pos);

        RoleEquipField roleEquipField = new RoleEquipField();
        roleEquipField.setType((short) 1);
        String color = "绿色";
        LinkedHashMap<Short, FiedValue> basicAttrNew = equipService.getBasicAttrNew(equip, roleEquip, color, true);
        roleEquipField.setField(basicAttrNew);
        roleEquip.getFields().put(roleEquipField.getType(), roleEquipField);
        RoleEquipField basicAttNew = equipService.getBasicAttNew(equip);
        roleEquip.getFields().put(basicAttNew.getType(), basicAttNew);
        HashMap<Short, String> attribs = new HashMap<>();
        attribs.put((short) 514, makeEquip.getBlue());
        attribs.put((short) 770, makeEquip.getPink());
        attribs.put((short) 1026, makeEquip.getYellow());
        attribs.put((short) 2050, makeEquip.getBlack());
        attribs.put((short) 3074, makeEquip.getGreen());
//        attribs.put((short) 6914, makeEquip.getGongming()); Todo 共鸣属性不好搞 先不搞算了
        List<RoleEquipField> equipFields = new ArrayList<>();
        attribs.forEach((key, values) -> {
            if(values == null){
                return;
            }
            RoleEquipField extraAttrib = new RoleEquipField();
            extraAttrib.setType(key);
            LinkedHashMap<Short, FiedValue> linkedHashMap = new LinkedHashMap<>();
            extraAttrib.setField(linkedHashMap);
            if (values.contains("|")) {//多条属性代表是蓝色的
                String[] blues = values.split("\\|");
                for (String attrib : blues) {
                    String[] value = attrib.split(":");
                    int fieldId = attrService.getFiledIdBy(value[0]);
                    linkedHashMap.put((short) fieldId, new FiedValue(fieldId, Integer.parseInt(value[1])));
                }
            } else {
                String[] value = values.split(":");
                int fieldId = attrService.getFiledIdBy(value[0]);
                linkedHashMap.put((short) fieldId, new FiedValue(fieldId, Integer.parseInt(value[1])));
            }
            equipFields.add(extraAttrib);
        });
        equipFields.forEach(fields -> roleEquip.getFields().put(fields.getType(), fields));

        if( makeEquip.getBlack() != null) {
            String fieldName = makeEquip.getBlack().split(":")[0];
            int attribId = attrService.getFiledIdBy(fieldName);
            //logger.error("装备相性={}", polars.indexOf(attribId));
            roleEquip.alterSuitPolar(polars.indexOf(attribId));
        }
        roleEquip.alterUpgradeLevel(makeEquip.getRebuildLevel());
        equipService.addUpgradeField(equip, roleEquip);
        equipService.add(role, roleEquip);
        equipService.refreshRoleEquip(role, roleEquip);
        MessagePusher.pushMessage(role, new RespIconCartoon(roleEquip.getName()));

        //logger.error("GM生成装备=name={}=装备={}", role.getName(), equipName);

        /**产生一个装备改造等级改变事件*/
        EventDispatcher.getInstance().fireEvent(new EquipUpgradeLevelChangeEvent(EventType.EQUIP_UPGRADE_LEVEL_CHANGE, role, roleEquip, roleEquip.queryUpgradeLevel()));
    }


    private String getEquipName(int level, String type) {
        for (Map.Entry<String, Object> entry : MarketDataPool.marketDatas.entrySet()) {
            String key = entry.getKey();
            NutMap map = (NutMap) entry.getValue();
            Object object = map.get("level");
            if (object instanceof Integer) {
                if ((int) object == level) {
                    if (map.getString("subClass").equals("装备") && map.getString("secondClass").equals(type)) {
                        return key;
                    }
                }
            }

        }
        return null;
    }

    /**
     * 查询角色
     */
    public void queryPlayer(Role gm, String name, String type) {
        Account account;
        if (type.equals("name")) {
            RespAdminQueryPlayer adminQueryPlayer = new RespAdminQueryPlayer();
            Role role = SpringUtils.getRoleService().getOnlinePlayer(name);
            if (role == null) {
                role = SpringUtils.getRoleService().getOnlinePlayerFromDB(name);
                if (role == null){
                    MessagePusher.pushMessage(gm, adminQueryPlayer);
                    return;
                }
            }
            IoSession session = SessionUtils.getSessionBy(role.getId());
            if (session == null) {
                account = accountService.getAccount(role.getSid());
                QueryPlayer queryPlayer = new QueryPlayer(account, role, "离线", serverService.getServer().getName());
                adminQueryPlayer.setPlayers(Collections.singletonList(queryPlayer));
                MessagePusher.pushMessage(gm, adminQueryPlayer);
                return;
            }
            account = accountService.getAccount(role.getSid());
            QueryPlayer queryPlayer = new QueryPlayer(account, role, session.getRemoteAddress().toString(), serverService.getServer().getName());
            adminQueryPlayer.setPlayers(Collections.singletonList(queryPlayer));
            MessagePusher.pushMessage(gm, adminQueryPlayer);
        }
    }

    /**
     * 封闭Mac
     */
    public void blockAccount(Account blockAccount) {
        blockAccount.setIsStop(1);
        Db4CommonService.getInstance().add2Queue(blockAccount);
        accountService.addBanedDevice(blockAccount.getDeviceInfo());
        accountService.addBanedPhone(blockAccount.getUsername());
    }
    /**
     * 解除封闭Mac
     */
    public void writeAccount(Account blockAccount) {
        blockAccount.setIsStop(0);
        Db4CommonService.getInstance().add2Queue(blockAccount);
        accountService.delBanedDevice(blockAccount.getDeviceInfo());
        accountService.delBanedPhone(blockAccount.getUsername());
    }

    /**
     * 封闭IP
     */
    private void blockIp(IoSession session) {
        String ipAddr = session.getRemoteAddress().toString().split(":")[0].replace("/", "");
        accountService.addBanedIP(ipAddr);
    }

    /**
     * 禁言角色
     */
    public void shutChannel(Role target, long time) {
        if (time <= 0) {
            target.setWordTime(0);
        } else {
            target.setWordTime(time);
        }
        target.save();
    }

    /**
     * 封闭角色
     */
    public void blockPlayer(Role target, long time) {
        if (time <= 0) {
            target.setLockTime(0);
        } else {
            target.setLockTime(time);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date = new Date(target.getLockTime());
            String tips = simpleDateFormat.format(date);

            RespOtherLogin respOtherLogin = new RespOtherLogin();
            respOtherLogin.setContent("当前角色被封闭至#R" + tips + "#n。");
            respOtherLogin.setResult((short) 2);
            MessagePusher.pushMessage(target, respOtherLogin);
        }
        target.save();
    }
}
